<template>
    <div>
        <div style="display: flex;justify-content: space-between;">
            <div class="search-term">
                <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
                    <el-form-item label="">
                        <el-input placeholder="文件名字" v-model="searchInfo.fileName"></el-input>
                    </el-form-item>
                    <el-form-item label="">
                        <el-input placeholder="文件MD5" v-model="searchInfo.fileMd5"></el-input>
                    </el-form-item>
                    <el-form-item label="">
                        <el-input placeholder="文件描述" v-model="searchInfo.fileMemo"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="onSubmit" type="primary">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div>
                <uploader
                        :options="options"
                        :file-status-text="statusText"
                        :autoStart="false"
                        @file-added="fileAdded"
                        @file-progress="onFileProgress"
                        @file-success="onFileSuccess"
                        @file-error="onFileError"
                        class="uploader-example"
                >
                    <uploader-unsupport></uploader-unsupport>
                    <uploader-drop>
                        <uploader-btn>点击或拖拽上传</uploader-btn>
                    </uploader-drop>
                    <uploader-list></uploader-list>
                </uploader>
            </div>
        </div>
        <el-table
                :data="tableData"
                @selection-change="handleSelectionChange"
                border
                ref="multipleTable"
                stripe
                style="width: 100%"
                tooltip-effect="dark"
        >
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-form class="demo-table-expand">
                        <el-form-item label="文件名" style="width:100%">
                            <div>{{ props.row.fileName }}</div>
                        </el-form-item>
                        <el-form-item label="MD5">
                            <span>{{ props.row.fileMd5 }}</span>
                        </el-form-item>
                        <el-form-item label="大小">
                            <span>{{ props.row.fileSize }}</span>
                        </el-form-item>
                        <el-form-item label="描述" style="width:100%;">
                            <div>{{props.row.fileMemo }}</div>
                        </el-form-item>
                        <el-form-item label="上传者">
                            <span>{{ props.row.fileAuthor }}</span>
                        </el-form-item>
                        <el-form-item label="日期">
                            <span>{{props.row.CreatedAt|formatDate}}</span>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column label="文件名字" prop="fileName" width="360" :show-overflow-tooltip="overflow"></el-table-column>
            <el-table-column label="MD5" prop="fileMd5" width="280" :show-overflow-tooltip="overflow"></el-table-column>
            <el-table-column label="字节" prop="fileSize" width="80" :show-overflow-tooltip="overflow"></el-table-column>

            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-view" size="mini" @click="viewRow(scope.row)">预览
                    </el-button>
                    <el-button type="info" icon="el-icon-copy-document" size="mini" @click="copyUri(scope.row)">复制
                    </el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRow(scope.row)">删除
                    </el-button>
                    <el-button type="warning" icon="el-icon-download" size="mini" @click="download(scope.row)">下载
                    </el-button>
                    <el-button class="table-button" @click="updateFileManager(scope.row)" size="small" type="primary"
                               icon="el-icon-edit">变更
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
                :current-page="page"
                :page-size="pageSize"
                :page-sizes="[10, 30, 50, 100]"
                :style="{float:'right',padding:'20px'}"
                :total="total"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
                layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
        <el-dialog :before-close="closeDialog" :visible.sync="dialogFormVisible" title="编辑描述">
            <el-form :rules="rules" :model="formData" ref="fileManagerForm" label-position="right" label-width="80px">
                <el-form-item label="描述:" label-width="80px" prop="tagName">
                    <el-input v-model="formData.fileMemo" clearable placeholder="请输入"></el-input>
                </el-form-item>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button @click="enterDialog" type="primary">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import {
        createFileManager,
        deleteFileManager,
        deleteFileManagerByIds,
        updateFileManager,
        findFileManager,
        getFileManagerList
    } from "@/api/file_manager";  //  此处请自行替换地址
    import {formatTimeToStr} from "@/utils/date";
    import {downloadFile} from "../../api/excel";
    import infoList from "@/mixins/infoList";

    var notUploadedChunks = []; // 已经上传过的文件chunkNumber数组
    var isUploaded = false; // 文件已经上传成功了
    import {mapGetters} from "vuex";
    import {checkFileMd5, mergeFileMd5} from "@/api/simpleUploader";
    import SparkMD5 from "spark-md5";

    const path = process.env.VUE_APP_BASE_API;
    export default {
        name: "FileManager",
        mixins: [infoList],
        data() {
            return {
                md5: "",
                listApi: getFileManagerList,
                dialogFormVisible: false,
                type: "",
                overflow: true,
                deleteVisible: false,
                multipleSelection: [], formData: {
                    fileName: "",
                    fileType: "",
                    fileAuthor: "",
                    fileUri: "",

                }
            };
        },
        filters: {
            formatDate: function (time) {
                if (time != null && time != "") {
                    var date = new Date(time);
                    return formatTimeToStr(date, "yyyy-MM-dd hh:mm:ss");
                } else {
                    return "";
                }
            },
            formatBoolean: function (bool) {
                if (bool != null) {
                    return bool ? "是" : "否";
                } else {
                    return "";
                }
            }
        },
        computed: {
            ...mapGetters("user", ["userInfo", "token"]),
            statusText() {
                return {
                    success: "成功了",
                    error: "出错了",
                    uploading: "上传中",
                    paused: "暂停中",
                    waiting: "等待中"
                };
            },
            options() {
                return {
                    target: path + "/simpleUploader/upload",
                    testChunks: false,
                    simultaneousUploads: 5,
                    chunkSize: 2 * 1024 * 1024,
                    headers: {
                        "x-token": this.token,
                        "x-user-id": this.userInfo.ID
                    },
                    checkChunkUploadedByResponse(chunk) {
                        if (isUploaded) {
                            return true; // return true 会忽略当前文件，不会再发送给后台
                        } else {
                            // 根据已经上传过的切片来进行忽略
                            return (

                                notUploadedChunks &&
                                notUploadedChunks.some(
                                    item => item.chunkNumber == chunk.offset + 1
                                )
                            );
                        }
                    }
                };
            }
        },
        methods: {
            //条件搜索前端看此方法
            onSubmit() {
                this.page = 1
                this.pageSize = 10
                this.getTableData()
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
            },
            deleteRow(row) {
                this.$confirm('确定要删除吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.deleteFileManager(row);
                })
            },
            viewRow(row) {
                if (row.fileType == "png" || row.fileType == "jpg" || row.fileType == "jpeg"
                    || row.fileType == "pdf" || row.fileType == "mp4" || row.fileType == "webm"
                    || row.fileType == "ogg" || row.fileType == "mpeg" || row.fileType == "wav"
                    || row.fileType == "apng" || row.fileType == "avif" || row.fileType == "bmp"
                    || row.fileType == "gif" || row.fileType == "ico" || row.fileType == "jfif"
                    || row.fileType == "pjpeg" || row.fileType == "pjp" || row.fileType == "svg"
                    || row.fileType == "tif" || row.fileType == "tiff" || row.fileType == "webp") {
                    window.open(row.fileUri);
                } else if (row.fileType == "ppt" || row.fileType == "pptx" || row.fileType == "xlsx" || row.fileType == "xls" || row.fileType == "doc" || row.fileType == "docx") {
                    let url = 'office.html?' + encodeURI(row.fileUri + '&' + row.fileName + '&' + row.fileType);
                    window.open(url);
                } else {
                    this.$message({
                        type: 'warning',
                        message: '此格式，暂不支持预览'
                    })
                }
            },
            download(row) {

                if (row.fileType == "png" || row.fileType == "jpg" || row.fileType == "jpeg"
                    || row.fileType == "pdf" || row.fileType == "mp4" || row.fileType == "webm"
                    || row.fileType == "ogg" || row.fileType == "mpeg" || row.fileType == "wav"
                    || row.fileType == "apng" || row.fileType == "avif" || row.fileType == "bmp"
                    || row.fileType == "gif" || row.fileType == "ico" || row.fileType == "jfif"
                    || row.fileType == "pjpeg" || row.fileType == "pjp" || row.fileType == "svg"
                    || row.fileType == "tif" || row.fileType == "tiff" || row.fileType == "webp") {
                    downloadFile(row.fileName)
                } else if (row.fileType == "ppt" || row.fileType == "pptx" || row.fileType == "xlsx" || row.fileType == "xls" || row.fileType == "doc" || row.fileType == "docx") {
                    downloadFile(row.fileName)
                } else {
                    window.open(row.fileUri);
                }
            }
            ,
            copyUri(row) {

                this.$copyText(
                    row.fileUri
                ).then(res => {
                        //这是element的Message 消息提示组件
                        this.$message({
                            message: "复制成功",
                            type: "success"
                        });
                        console.log(res)
                    },
                    err => {
                        this.$message.error("复制失败");
                        console.log(err)
                    }
                );
            },
            async onDelete() {
                const ids = []
                if (this.multipleSelection.length == 0) {
                    this.$message({
                        type: 'warning',
                        message: '请勾选'
                    })
                    return
                }
                this.multipleSelection &&
                this.multipleSelection.map(item => {
                    ids.push(item.ID)
                })
                const res = await deleteFileManagerByIds({ids})
                if (res.code == 0) {
                    this.$message({
                        type: 'success',
                        message: '删除成功'
                    })
                    if (this.tableData.length == ids.length) {
                        this.page--;
                    }
                    this.deleteVisible = false
                    this.getTableData()
                }
            },
            async updateFileManager(row) {
                const res = await findFileManager({ID: row.ID});
                this.type = "update";
                if (res.code == 0) {
                    this.formData = res.data.refileManager;
                    this.dialogFormVisible = true;
                }
            },
            closeDialog() {
                this.dialogFormVisible = false;
                this.formData = {
                    fileName: "",
                    fileType: "",
                    fileAuthor: "",
                    fileUri: "",

                };
            },
            async deleteFileManager(row) {
                const res = await deleteFileManager({ID: row.ID});
                if (res.code == 0) {
                    this.$message({
                        type: "success",
                        message: "删除成功"
                    });
                    if (this.tableData.length == 1) {
                        this.page--;
                    }
                    this.getTableData();
                }
            },
            async enterDialog() {
                let res;
                switch (this.type) {
                    case "create":
                        res = await createFileManager(this.formData);
                        break;
                    case "update":
                        res = await updateFileManager(this.formData);
                        break;
                    default:
                        res = await createFileManager(this.formData);
                        break;
                }
                if (res.code == 0) {
                    this.$message({
                        type: "success",
                        message: "创建/更改成功"
                    })
                    this.closeDialog();
                    this.getTableData();
                }
            },
            openDialog() {
                this.type = "create";
                this.dialogFormVisible = true;
            }
            ,
            // 上传单个文件
            fileAdded(file) {
                this.computeMD5(file); // 生成MD5
            },
            // 计算MD5值
            computeMD5(file) {
                var that = this;
                isUploaded = false; // 这个文件是否已经上传成功过
                notUploadedChunks = []; // 未成功的chunkNumber
                var fileReader = new FileReader();
                var md5 = "";

                file.pause();

                fileReader.readAsArrayBuffer(file.file);
                fileReader.onload = async function (e) {
                    if (file.size != e.target.result.byteLength) {
                        this.error(
                            "Browser reported success but could not read the file until the end."
                        );
                        return false;
                    }
                    md5 = SparkMD5.ArrayBuffer.hash(e.target.result, false);

                    file.uniqueIdentifier = md5;
                    if (md5 != "") {
                        const res = await checkFileMd5({md5: md5});
                        if (res.code == 0) {
                            if (res.data.isDone) {
                                // 上传成功过
                                isUploaded = true;
                                that.$message({
                                    message: "该文件已经上传成功过了，秒传成功。",
                                    type: "success"
                                });

                                file.cancel();
                            } else {
                                isUploaded = false;
                                notUploadedChunks = res.data.chunks;
                                if (notUploadedChunks.length) {
                                    file.resume();
                                } else if (notUploadedChunks.length == 0) {
                                    file.resume();
                                }
                            }
                        }
                    }


                };
                fileReader.onerror = function () {
                    this.error(
                        "generater md5 时FileReader异步读取文件出错了，FileReader onerror was triggered, maybe the browser aborted due to high memory usage."
                    );
                    return false;
                };
            },
            // 上传进度
            onFileProgress() {
            },
            // 上传成功
            async onFileSuccess(rootFile, file) {
                await mergeFileMd5({md5: file.uniqueIdentifier, fileName: file.name})
                await this.getTableData();
            },
            onFileError(rootFile, file, response) {
                this.$message({
                    message: response,
                    type: "error"
                });
            }
        },
        async created() {
            await this.getTableData();

        }
    };
</script>

<style>
    .uploader-example {
        width: 500px;
        font-size: 12px;
        margin-bottom: 10px;
    }

    .uploader-example .uploader-btn {
        margin-right: 4px;
    }

    .uploader-example .uploader-list {
        max-height: 440px;
        overflow: auto;
        overflow-x: hidden;
        overflow-y: auto;
    }
    .demo-table-expand {
        font-size: 0;
    }

    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }

    .demo-table-expand .el-form-item {
        margin-left: 0;
        margin-bottom: 0;
        width: 50%;
    }
</style>
